<template>
  <d2-container>
    <div class="pt-3">
      <el-form :model="form" label-width="100px" ref="form" :rules="formRules">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="first">
            <div style="width: 45%;" class="mt-3">
              <el-form-item label="产品名称" prop="product_name">
                <el-input v-model="form.product_name" placeholder="产品名称"></el-input>
              </el-form-item>
            </div>
            <div style="width: 45%;">
              <el-form-item label="产品副名称" prop="sub_name">
                <el-input v-model="form.sub_name" placeholder="产品副名称"></el-input>
              </el-form-item>
            </div>
            <div class="row-ac">
              <div>
                <el-form-item label="分类" prop="category">
                  <el-cascader v-model="form.category" :props="{value:'id', label: 'category_name'}"
                    :options="categoriesTree" :show-all-levels="false" placeholder="请选择分类" @change="updateCategory" />
                </el-form-item>
              </div>
              <div>
                <el-form-item label="品牌" prop="brand">
                  <el-select v-model="form.brand" placeholder="请选择品牌">
                    <el-option v-for="item1 in brandsList" :key="item1.id" :label="item1.brand_name"
                      :value="item1.id"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div style="width: 80%;">
              <el-form-item label="产品相册" prop="image_list">
                <el-upload :action="actionUrl" list-type="picture-card" :on-remove="handleRemove"
                  :on-success="handleSuccess" :file-list="form.image_list" :headers="headersobj">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </div>
            <div class="row-ac">
              <div>
                <el-form-item label="商品售价" prop="price">
                  <el-input-number v-model="form.price" :precision="2" :min="0" :step="0.01"></el-input-number>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="市场售价" prop="mar_price">
                  <el-input-number v-model="form.mar_price" :precision="2" :min="0" :step="0.01"></el-input-number>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="成本价格" prop="cost_price">
                  <el-input-number v-model="form.cost_price" :precision="2" :min="0" :step="0.01"></el-input-number>
                </el-form-item>
              </div>
            </div>
            <div class="row-ac">
              <div>
                <el-form-item label="库存" prop="inventory">
                  <el-input-number v-model="form.inventory" :min="0"></el-input-number>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="销量" prop="sales_volume">
                  <el-input-number v-model="form.sales_volume" :min="0"></el-input-number>
                </el-form-item>
              </div>

            </div>
            <div class="row-ac">
              <div>
                <el-form-item label="关注数" prop="follow">
                  <el-input-number v-model="form.follow" :min="0"></el-input-number>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="获得积分" prop="score">
                  <el-input-number v-model="form.score" :min="0"></el-input-number>
                </el-form-item>
              </div>
            </div>
            <div class="row-ac">
              <div>
                <el-form-item label="是否推荐" prop="is_recommend">
                  <el-switch v-model="form.is_recommend"></el-switch>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="是否热门" prop="is_hot">
                  <el-switch v-model="form.is_hot"></el-switch>
                </el-form-item>
              </div>
              <div class="ml-5">
                <el-form-item label="是否新品" prop="is_new">
                  <el-switch v-model="form.is_new"></el-switch>
                </el-form-item>
              </div>
            </div>
            <div style="width: 18%;">
              <el-form-item label="排序" prop="sort">
                <el-input v-model="form.sort" placeholder="排序"></el-input>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品规格" name="specifications">
            <div style="width: 80%;" class="mt-3 ml-3">
              <el-form-item label="规格设置" prop="variant">
                <el-radio-group v-model="form.variant" @change="handleVariantChange">
                  <el-radio :label="0">单规格</el-radio>
                  <el-radio :label="1">多规格</el-radio>
                </el-radio-group>
              </el-form-item>
              <div class="mt-2 flex-1" v-if="form.variant == 1">
                <div style="width: 80%;">
                  <div class="row-ac flex-1">
                    <div class="font-s-2 text-light-grey">规格列表</div>
                    <div class="ml-3"><el-button size="mini" type="danger" @click="addSkuName">添加规格类型</el-button></div>
                  </div>
                  <div class="flex-1 mt-5 ml-8" v-if="proSkus && proSkus.length">
                    <div class="flex-1 mb-5" v-for="sku in proSkus" :key="sku.id">
                      <div class="flex-1 row-ac">
                        <div class="font-s-3 font-w mr-2">{{ sku.name }}</div>
                        <div class="mr-5"><el-button type="warning" size="mini" @click="addAttribute(sku.id)"
                            plain>添加规格值</el-button></div>
                        <el-button type="info" plain size="mini" @click="editSkuDialog(sku.id)" plain>编辑</el-button>
                        <el-button type="info" plain size="mini" @click="editSkuDelete(sku.id)" plain>删除</el-button>
                      </div>
                      <div class="flex-1 mt-3">
                        <template>
                          <el-table :data="sku.atributeList" style="width: 100%" :border="false">
                            <el-table-column label="序号" type="index" width="50" header-align="center" align="center">
                            </el-table-column>
                            <el-table-column align="center" label="规格图片" prop="image" width="80">
                              <template slot-scope="scope">
                                <el-popover placement="right" trigger="hover" v-if="scope.row.attr_img">
                                  <el-image slot="reference" style="width: 40px; height: 40px" :src="scope.row.attr_img"
                                    fit="cover" />
                                  <el-image style="width: 220px; height: 220px" :src="scope.row.attr_img"
                                    fit="contain" />
                                </el-popover>
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="规格值" prop="name" width="70" />
                            <el-table-column align="center" label="规格价格" prop="Attr_price" width="80" />
                            <el-table-column align="center" label="库存" prop="stock" width="80" />
                            <el-table-column align="center" label="操作" width="230">
                              <template slot-scope="scope">
                                <el-button size="mini" @click="handleAttrEdit(scope.row.id)">修改</el-button>
                                <el-button size="mini" type="danger" @click="openDelete(scope.row.id)">删除</el-button>
                              </template>
                            </el-table-column>
                          </el-table>
                        </template>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="details">
            <div style="width: 80%;height: 600px;" class="mt-3">
              <el-form-item prop="content">
                <d2-quill v-model="form.details" />
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="营销设置" name="marketing">
            <div class="mt-5 row-ac">
              <el-form-item :label="form.is_distribution == false ? '开启分销' : '关闭分销'" prop="is_distribution">
                <el-switch v-model="form.is_distribution"></el-switch>
              </el-form-item>
              <div class="ml-4 font-s-2 text-light-muted mb-1">分销功能开启后商品才能进行分销</div>
            </div>
            <div class="mt-2 row-ac" v-if="form.is_distribution == true">
              <el-form-item label="分销佣金" prop="commission">
                <el-input-number v-model="form.commission" :precision="2" :min="0" :step="0.01"></el-input-number>
              </el-form-item>
              <div class="ml-4 font-s-2 text-light-muted mb-1">佣金金额为分销商的返佣金额</div>
            </div>
            <div class="mt-2 row-ac" v-if="form.is_distribution == true">
              <el-form-item label="间点奖" prop="middle_reward">
                <el-input-number v-model="form.middle_reward" :precision="2" :min="0" :step="0.01"></el-input-number>
              </el-form-item>
              <div class="ml-4 font-s-2 text-light-muted mb-1">佣金金额为分销商的返佣金额</div>
            </div>
            <div class="mt-5 row-ac">
              <el-form-item :label="form.is_escalate == false ? '开启升级身份' : '关闭升级身份'" prop="is_escalate">
                <el-switch v-model="form.is_escalate"></el-switch>
              </el-form-item>
              <div class="ml-4 font-s-2 text-light-muted mb-1">分销功能开启后商品才能进行分销</div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="row" style="width: 80%;margin-top: 20px;">
          <el-form-item>
            <el-button plain @click="submitForm('drafts')">保存到草稿</el-button>
            <el-button type="primary" @click="submitForm('submit')">保存并提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog title="添加规格类型" :visible.sync="dialogFormSkuVisible" width="40%">
      <el-form :model="skuForm" label-width="80px" ref="form">
        <el-form-item label="规格名称" prop="name">
          <div style="width: 50%;">
            <el-input size="small" v-model="skuForm.name"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <div style="width: 40%;">
            <el-input size="small" v-model="skuForm.sort"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormSkuVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="comfireSkuName">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加规格值" :visible.sync="dialogAttributeVisible" width="40%">
      <el-form :model="attributeForm" label-width="80px" ref="form">
        <el-form-item label="值名称" prop="name">
          <div style="width: 50%;">
            <el-input size="small" v-model="attributeForm.name"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="图片" prop="attr_img">
          <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false" :on-success="handleattrSuccess"
            :headers="headersobj">
            <img v-if="attributeForm.attr_img" :src="attributeForm.attr_img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="库存" prop="sort">
          <div style="width: 40%;">
            <el-input size="small" v-model="attributeForm.stock"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <div style="width: 40%;">
            <el-input size="small" v-model="attributeForm.sort"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogAttributeVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="comfireAttribute">确 定</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
  import util from '@/libs/util'
  import {
    brandsListUrl,
    imagesUploadUrl
  } from '@/utils/interface'
  import {
    patch
  } from '@/utils/request'
  import {
    productCategoriesTreeUrl,
    productCreateUrl,
    productUpdateUrl,
    productDetailUrl,
    productPatchUrl,
    propertiesCreateUrl,
    propertiesDetailUrl,
    propertiesUpdateUrl,
    propertiesDeleteUrl,
    attributevalueDeleteUrl,
    attributevalueUpdateUrl,
    attributevalueCreateUrl,
    attributevalueDetailUrl,
    attributevalueListUrl,
  } from '@/utils/product'
  import {
    baseURL
  } from '@/utils/request'
  import d2Quill from '@/components/d2-quill'
  export default {
    components: {
      d2Quill
    },
    data() {
      return {
        form: {
          product_name: '',
          sub_name: '',
          category: '',
          brand: '',
          image_list: [],
          price: '',
          mar_price: '',
          cost_price: '',
          inventory: 0,
          sales_volume: 0,
          follow: 0,
          is_recommend: false,
          is_hot: false,
          is_new: false,
          is_distribution: false,
          commission: 0,
          middle_reward: 0,
          is_escalate: false,
          sort: '',
          details: '',
          product_state: 0,
          variant: 0,
          score: 0
        },
        formRules: {
          product_name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          category: [{
            required: true,
            message: '请选择商品分类',
            trigger: 'change'
          }],
          brand: [{
            required: true,
            message: '请选择商品品牌',
            trigger: 'change'
          }],
          details: [{
            required: true,
            message: '请填写商品详情',
            trigger: 'blur'
          }],
        },
        treeProps: {
          value: 'id',
          label: 'category_name'
        },
        activeName: 'first',
        valueChange: '',
        categoriesTree: [],
        brandsList: [],
        baseURL: baseURL,
        editor: null,
        toolbarConfig: {},
        editorConfig: {
          placeholder: '请输入内容...'
        },
        mode: 'default', // or 'simple'
        imageList: [],
        actionUrl: baseURL + imagesUploadUrl,
        getProductId: '',
        proSkus: [],
        dialogFormSkuVisible: false,
        addSkuNameStatu: true,
        skuForm: {
          name: '',
          product: '',
          sort: 0
        },
        getPropertiesId: '',
        dialogAttributeVisible: false,
        addAttributeStatu: true,
        attributeForm: {
          name: '',
          attr_img: '',
          properties: '',
          sort: 1,
          stock: 1
        },
        getAttrId: '',
        fileList: [],
        headersobj: null,
      }
    },
    mounted() {
      if (this.$route.query.productId) {
        this.getProductId = this.$route.query.productId
        this.getProductDetail()
      }
      this.headersobj = {
        Authorization: 'Bearer ' + util.cookies.get('token')
      }
      console.log(this.headersobj);
    },
    created() {
      this.$get(productCategoriesTreeUrl).then(res => {
        this.categoriesTree = res.data.data.list
        this.form.category = this.categoriesTree[0].id
      })
      this.$get(brandsListUrl).then(res => {
        this.brandsList = res.data.data.list
        this.form.brand = this.brandsList[0].id
      })
    },
    methods: {
      handleClick(tab, event) {

      },
      getProductDetail() {
        this.$get(productDetailUrl + this.getProductId + '/').then(res => {
          this.form = {
            product_name: res.data.data.product_name,
            sub_name: res.data.data.sub_name,
            category: res.data.data.category,
            brand: res.data.data.brand,
            image_list: res.data.data.image_list,
            price: res.data.data.price,
            mar_price: res.data.data.mar_price,
            cost_price: res.data.data.cost_price,
            inventory: res.data.data.inventory,
            sales_volume: res.data.data.sales_volume,
            follow: res.data.data.follow,
            is_recommend: res.data.data.is_recommend,
            is_hot: res.data.data.is_hot,
            is_new: res.data.data.is_new,
            is_distribution: res.data.data.is_distribution,
            commission: res.data.data.commission,
            middle_reward: res.data.data.middle_reward,
            is_escalate: res.data.data.is_escalate,
            sort: res.data.data.sort,
            details: res.data.data.details,
            product_state: res.data.data.product_state,
            variant: res.data.data.variant,
            score: res.data.data.score
          }
          this.imageList = res.data.data.image_list
          this.proSkus = res.data.data.skus
        })
      },
      updateCategory(value) {
        if (value && value.length > 0) {
          this.form.category = value[value.length - 1]; // 更新form.category的值为选中的最后一个值
        }
      },
      submitForm(type) {
        if (type == 'drafts') {
          this.form.product_state = 2
        } else if (type == 'submit') {
          this.form.product_state = 0
        }
        let formData = new FormData()
        formData.append('product_name', this.form.product_name)
        formData.append('sub_name', this.form.sub_name)
        formData.append('category', this.form.category)
        formData.append('brand', this.form.brand)
        formData.append('image_list', JSON.stringify(this.form.image_list))
        formData.append('price', this.form.price)
        formData.append('mar_price', this.form.mar_price)
        formData.append('cost_price', this.form.cost_price)
        formData.append('inventory', this.form.inventory)
        formData.append('sales_volume', this.form.sales_volume)
        formData.append('follow', this.form.follow)
        formData.append('is_recommend', this.form.is_recommend)
        formData.append('is_hot', this.form.is_hot)
        formData.append('is_new', this.form.is_new)
        formData.append('is_distribution', this.form.is_distribution)
        formData.append('middle_reward', this.form.middle_reward)
        formData.append('commission', this.form.commission)
        formData.append('is_escalate', this.form.is_escalate)
        formData.append('sort', this.form.sort)
        formData.append('details', this.form.details)
        formData.append('product_state', this.form.product_state)
        formData.append('variant', this.form.variant)
        formData.append('score', this.form.score)
        this.$put(productUpdateUrl + this.getProductId + '/', formData).then(res => {
          this.form = {}
          this.openPrompt()
          setTimeout(() => {
            this.$router.go(-1)
          }, 300) // 延迟1秒执行
        })
      },
      openPrompt() {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
      },
      handleSuccess(response, file) {
        this.imageList.push({
          url: response.data.url
        })
        this.form.image_list = this.imageList
        console.log(response.data.url);
        console.log(this.form.image_list);
      },
      handleRemove(file, fileList) {
        const index = this.form.image_list.findIndex((item) => item.url === file.url);
        if (index !== -1) {
          this.form.image_list.splice(index, 1);
        } else if (this.form.image_list.length > 0) {
          this.form.image_list.pop();
        }
      },
      handleVariantChange(newVal) {
        patch(productPatchUrl + this.getProductId + '/', {
          variant: newVal
        }).then(res => {
          this.getProductDetail()
        });
      },
      addSkuName() {
        this.dialogFormSkuVisible = true
        this.addSkuNameStatu = true
      },
      comfireSkuName() {
        this.skuForm.product = this.getProductId
        if (this.addSkuNameStatu) {
          this.$post(propertiesCreateUrl, this.skuForm).then(res => {
            if (res.data.code == 200) {
              this.dialogFormSkuVisible = false
              this.$message.success('添加成功')
              this.skuForm = {}
              this.getProductDetail()
            }
          })
        } else {
          this.$put(propertiesUpdateUrl + this.getPropertiesId + '/', this.skuForm).then(res => {
            if (res.data.code == 200) {
              this.dialogFormSkuVisible = false
              this.$message.success('修改成功')
              this.skuForm = {}
              this.getProductDetail()
            }
          })
        }
      },
      editSkuDialog(propertiesId) {
        this.dialogFormSkuVisible = true
        this.addSkuNameStatu = false
        this.getPropertiesId = propertiesId
        this.$get(propertiesDetailUrl + propertiesId + '/').then(res => {
          if (res.data.code == 200) {
            this.skuForm = {
              name: res.data.data.name,
              product: res.data.data.product,
              sort: res.data.data.sort,
            }
          }
        })
      },
      editSkuDelete(propertiesId) {
        this.$confirm('此操作将永久删除该规格, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 在确定时执行handleDelete的删除
          this.$del(propertiesDeleteUrl + propertiesId + '/').then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getProductDetail()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleattrSuccess(val) {
        this.attributeForm.attr_img = val.data.url
      },
      addAttribute(propertiesId) {
        this.dialogAttributeVisible = true
        this.addAttributeStatu = true
        this.getPropertiesId = propertiesId
      },
      comfireAttribute() {
        if (this.addAttributeStatu) {
          this.attributeForm.properties = this.getPropertiesId
          this.$post(attributevalueCreateUrl, this.attributeForm).then(res => {
            if (res.data.code == 200) {
              this.dialogAttributeVisible = false
              this.$message.success('添加成功')
              this.attributeForm = {}
              this.getProductDetail()
            }
          })
        } else {
          this.$put(attributevalueUpdateUrl + this.getAttrId + '/', this.attributeForm).then(res => {
            if (res.data.code == 200) {
              this.dialogAttributeVisible = false
              this.$message.success('修改成功')
              this.attributeForm = {}
              this.getProductDetail()
            }
          })
        }
      },
      handleAttrEdit(attrId) {
        this.dialogAttributeVisible = true
        this.addAttributeStatu = false
        this.getAttrId = attrId
        this.$get(attributevalueDetailUrl + attrId + '/').then(res => {
          if (res.data.code == 200) {
            this.attributeForm = {
              name: res.data.data.name,
              attr_img: res.data.data.attr_img,
              properties: res.data.data.properties,
              sort: res.data.data.sort,
              stock: res.data.data.stock
            }
          }
        })
      },
      openDelete(attrId) {
        this.$confirm('此操作将永久删除该规格, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 在确定时执行handleDelete的删除
          this.$del(attributevalueDeleteUrl + attrId + '/').then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getProductDetail()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>

<style lang="scss">

</style>
